<template>
  <Modal v-model="currentModal" :title="formItem.id ? '编辑' : '新增'" :mask-closable="false" :closable="false">
    <Form :model="formItem" ref="fileForm" :rules="ruleValidate" :label-width="100">
      <FormItem label="姓名" prop="name">
        <Input v-model.trim="formItem.name" placeholder="请输入姓名"/>
      </FormItem>
      <FormItem label="年龄" prop="age">
        <Input v-model.trim="formItem.age" placeholder="请输入年龄"/>
      </FormItem>
      <FormItem label="家庭住址" prop="addess">
        <Input
          v-model="formItem.addess"
          type="textarea"
          :autosize="{minRows: 2,maxRows: 5}"
          placeholder
        ></Input>
      </FormItem>
    </Form>
    <div slot="footer">
      <Button @click="cancel()">取消</Button>
      <Button @click="confirm('fileForm')" type="primary">保存</Button>
    </div>
  </Modal>
</template>
<script>
export default {
  props: ['fileModal', 'formObj', 'saveOrUpdate'],
  data () {
    return {
      currentModal: false,
      formItem: {
        id: '',
        name: '',
        age: '',
        address: ''
      },
      ruleValidate: {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'fileModal': function (newVal) {
      this.currentModal = newVal
      // 根据编辑和新增给表单赋值和清空表单
      this.saveOrUpdate === 'save' ? (this.$refs.fileForm.resetFields()) : this.formItem = Object.assign({}, this.formObj)
    }
  },
  methods: {
    confirm (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$emit('handleConfirm', this.formItem)
        }
      })
    },
    cancel () {
      this.$emit('handleCancel')
    }
  }
}
</script>
